
import { Injectable } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import {Page, User, Token, UserRequest } from '@shared/bean';
import { Observable } from 'rxjs';
import {HttpHeaders} from '@angular/common/http';

@Injectable()
export class UserService {
    constructor(private http: _HttpClient) { }

    private _url = 'users';
    query(q?: any): Observable<Page> {
        return this.http.get(this._url, q);
    }

    findOne(id: number): Observable<User> {
        const url = `${this._url}/${id}`;
        return this.http.get(url);
    }

    create(user: User): Observable<User> {
        return this.http.post(this._url, user);
    }

    update(user: User): Observable<User> {
        return this.http.put(this._url, user);
    }

    delete(id: number): Observable<void> {
        const url = `${this._url}/${id}`;
        return this.http.delete(url);
    }

    exist(user: string): Observable<boolean> {
        const url = this._url + '/exist';
        return this.http.get(url, {user});
    }

    postForToken(params: any): Observable<Token> {
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .set('Authorization', 'Basic aW90LWVudm9vbDplbnZvb2wtc2Vj');

        return this.http.post('oauth/token', {}, params, {headers});
    }

    me(): Observable<User> {
        const url = this._url + '/me';
        return this.http.get(url);
    }

    register(userRequest: UserRequest): Observable<any> {
        const url = this._url + '/register';
        return this.http.post(url, userRequest);
    }

    resetPassword(userRequest: UserRequest): Observable<any> {
        const url = this._url + '/reset-password';
        return this.http.put(url, userRequest);
    }
}
